/*
 * Copyright (c) 2009. Silenus Consultoria, S.L.
 */
package es.silenus.detecta.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.IOException;
import java.io.StringWriter;

import java.util.Date;
import java.util.Locale;
import java.util.Map;


/**
 * Freemarker helper.
 *
 * @author <a href="mailto:malonso@silenus-consultoria.es">Mariano Alonso</a>
 *
 * @since 05-abr-2009 13:08:01
 */
public class FreemarkerHelper {
	/**
	 * The encoding.
	 */
	private String encoding;

	/**
	 * The freemarker configurer.
	 */
	private FreeMarkerConfigurer freemarkerConfigurer;

	/**
	 * Sets the encoding.
	 *
	 * @param encoding the encoding.
	 */
	public void setEncoding(final String encoding) {
		this.encoding = encoding;
	}

	/**
	 * Sets the freemarker configurer.
	 *
	 * @param freemarkerConfigurer the freemarker configurer.
	 */
	public void setFreemarkerConfigurer(final FreeMarkerConfigurer freemarkerConfigurer) {
		this.freemarkerConfigurer = freemarkerConfigurer;
	}

	/**
	 * Process a template and returns a string containing the processed text.
	 *
	 * @param templatePath the template path.
	 * @param locale the locale.
	 * @param encoding the encoding.
	 * @param model the model.
	 *
	 * @return the processed template.
	 *
	 * @throws IOException if reading template fails.
	 * @throws TemplateException if processing template fails.
	 */
	public String process(
		final String templatePath, final Locale locale, final String encoding, final Map<String, Object> model)
		throws IOException, TemplateException {
		// Load template
		Configuration configuration = freemarkerConfigurer.getConfiguration();
		Template template = configuration.getTemplate(templatePath, locale, encoding);

		// Add parameters to model.
		model.put("date", new Date());
		model.put("locale", locale);
		model.put("encoding", encoding);
		model.put("language", locale.getLanguage());

		// Process template
		StringWriter writer = new StringWriter();

		template.process(model, writer);
		writer.flush();


		return writer.toString();
	}

	/**
	 * Process a template and returns a string containing the processed text.
	 *
	 * @param templatePath the template path.
	 * @param model the model.
	 *
	 * @return the processed template.
	 *
	 * @throws IOException if reading template fails.
	 * @throws TemplateException if processing template fails.
	 */
	public String process(final String templatePath, final Map<String, Object> model)
		throws IOException, TemplateException {
		return process(templatePath, Locale.getDefault(), encoding, model);
	}
}
